#include "version.h"

Version::Version(QObject *parent) : QObject(parent)
{
    
}

Version::~Version()
{
    
    library->deleteLater();
    timer->stop();
    timer->deleteLater();
}

void Version::monitor()
{
    library = new Library();
    timer = new QTimer();
    connect(timer,&QTimer::timeout,this,&Version::getVersion);
    //timer->start(20000);
    
    //测试调用
    getVersion();
}

void Version::getVersion()
{
    qDebug()<<"getVersion";
    DownloadManager *download = new DownloadManager();
    QJsonObject object;
    object.insert("url","https://launchermeta.mojang.com/mc/game/version_manifest.json");
    object.insert("spec","./");
    connect(download,&DownloadManager::downloadFinsh,this,&Version::updateVersion); 
    download->append(object);
    //timer->start(1000);

}

void Version::updateVersion(QString versionJson)
{
    //timer->stop();
    qDebug()<<"updateVersion";
    QFile file(versionJson);
    if(!file.open(QIODevice::ReadOnly))
    {
        qDebug()<<"读取version_manifest.json失败";
        return;
    }
    QJsonObject obj = QJsonDocument::fromJson(file.readAll()).object();
    
    
    QString laRelease = obj["latest"].toObject()["release"].toString();
    //QString laSnapshot = obj["latest"].toObject()["snapshot"].toString();
    
     qDebug()<<"最新版本  "<<laRelease;
    QJsonArray arry = obj["versions"].toArray(); //获取记录不同版本的数组
    QJsonObject laJson;
    
    for(int i=0;i<arry.size();i++){
        if(arry[i].toObject()["id"].toString() == laRelease){
            qDebug()<<"下载地址  "<<arry[i].toObject()["url"].toString();
            laJson = arry[i].toObject();  //记录下载地址
            break;
        }
    }
    
    qDebug()<<"检查版本是否存在";
    //downloader 实例的时候是匿名的，现在根据信号发送者，释放掉
    static_cast<DownloadManager*>(sender())->deleteLater();
    
    //版本不存在就下载
    if(!library->isExist(laRelease))
    {
        DownloadManager *download = new DownloadManager(Config::getLibrary_path());
        connect(download,&DownloadManager::downloadFinsh,this,[=](QString fileName){
            qDebug()<<"Json 下载完成: "<<fileName;
            QFile file(fileName);
            if(!file.open(QIODevice::ReadOnly))
            {
                qDebug()<<"无法打开新版本的json: "<<fileName;
                download->deleteLater();
                return;
            }
            QByteArray buffer = file.readAll();
            file.close();
            
            QJsonParseError error;
            QJsonDocument document = QJsonDocument::fromJson(buffer,&error);
            if(error.error != QJsonParseError::NoError)
            {
                qDebug()<<"解析错误";
                download->deleteLater();
                return;
            }
            QJsonObject obj = document.object();
            download->deleteLater();
            parseJson(obj);
            
        });
        download->append(laJson);
    }
    
}

void Version::parseJson(QJsonObject obj)
{
    qDebug()<<"parseJson: ";
    library->update(obj);
}

